<?php
error_reporting(0);
//判断是否https
function is_https()
{
    if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        return true;
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
        return true;
    } elseif (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
        return true;
    } elseif (!empty($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], "https") === 0) {
        return true;
    }
    return false;
}

//获取文件缓存
function get_json($path)
{
    $data = file_get_contents($path);
    if (!$data) {
        return false;
    }
    $data = substr($data, strlen("<?php "));
    return json_decode($data, true);
}

//设置文件缓存
function set_json($path, $data)
{
    file_put_contents($path, "<?php " . json_encode($data));
}
function set_token($rootPath,$tokenData){
    set_json($rootPath."/token_data.php",$tokenData);
}
//创建多级目录
function create_dir($filePath)
{
    $filePath = str_replace('\\', '/', $filePath);
    $filePathList = explode("/", $filePath);
    $count = count($filePathList) - 1;
    for ($i = 0; $i < $count; $i++) {
        $path = implode("/", array_slice($filePathList, 0, $i + 1));
        if (!$path) {
            continue;
        }
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
    }
}

function path2name($path)
{
    $data = explode('/', $path);
    return $data[count($data) - 1];
}

//分离文件和目录
function fenli_name($dir)
{
    $pathSz = explode("/", $dir);
    $pathParent = "";
    $count = count($pathSz);
    $pathName = $pathSz[$count - 1];
    for ($x = 0; $x < $count - 1; $x++) {
        $path = $pathSz[$x];
        if ($path == "") {
            continue;
        }
        $pathParent = $pathParent . "/" . $path;
    }
    return array(
        "parentPath" => $pathParent,
        "currentPath" => $pathName
    );
}

//目录/文件 转id
function path2id($rootPath, $path)
{
    if ($path == "/") {
        $path = "";
    }
    //$rootPath 为 /data/wwwroot/kod.tenfell.cn/plugins/aliyunDrive/lib_file_328680
    if (!$path) {
        return "root";
    }
    $sz = fenli_name($path);
    $file_list = $rootPath . $sz['parentPath'] . "/" . "file_list.php";
    if (!file_exists($file_list)) {
        return "no_this_id";
    }
    $list = get_json($file_list);
    if (!$list || count($list) === 0) {
        return "no_this_id";
    }
    foreach ($list as $item) {
        if ($item['name'] === $sz['currentPath']) {
            return $item['file_id'];
        }
    }
    return "no_this_id";
}

//目录/文件 转pid
function path2pid($rootPath, $path)
{
    $parPath = fenli_name($path)['parentPath'];
    return path2id($rootPath, $parPath);
}

//目录/文件 转info
function path2info($rootPath, $path)
{
    //$rootPath 为 /data/wwwroot/kod.tenfell.cn/plugins/aliyunDrive/lib_file_328680
    if (!$path) {
        return false;
    }
    $sz = fenli_name($path);
    $file_list = $rootPath . $sz['parentPath'] . "/" . "file_list.php";
    if (!file_exists($file_list)) {
        return false;
    }
    $list = get_json($file_list);
    if (!$list || count($list) === 0) {
        return false;
    }
    foreach ($list as $item) {
        if ($item['name'] === $sz['currentPath']) {
            return $item;
        }
    }
    return false;
}

/**
 * ajax提交
 * @param $rootDir
 * @param $url
 * @param false $data
 * @param false $headers
 * @param false $type 类型  ajax:post json提交  content:获取内容 putfile:上传文件
 * @return mixed
 */
function aliRequest($rootDir, $url, $data = false, $headers = false, $type = false)
{
    if (!$type) {
        $type = "ajax";
    }
    $curl = curl_init();
    if (!str_start_with($url, "http")) {
        $url = 'https://api.aliyundrive.com' . $url;
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_REFERER, 'https://www.aliyundrive.com/');
    if ($type == "content") {
        curl_setopt($curl, CURLOPT_POST, 0);
    } else if ($type == "putfile") {
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
        if ($data) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
    } else if ($type == "ajax") {
        curl_setopt($curl, CURLOPT_POST, 1);
        if ($data) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
        }
    }

    if ($headers) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($curl);
    curl_errno($curl);
    curl_close($curl);
    if ($type == "ajax") {
        $res = json_decode($res, true);
        if ($res['code'] == "AccessTokenInvalid") {
            //权限不足,删除rootDir
            $flag = deldir($rootDir);
            logOut("删除主目录" . json_encode(
                    array(
                        "flag" => $flag,
                        "rootDir" => $rootDir
                    )));
        }
    }
    $text = "aliRequest:" . json_encode(array(
            'url' => $url,
            'type' => $type,
            'headers' => $headers,
            'res' => $type=="content"?false:$res
        ));
    logOut($text);
    if ($type == "ajax") {
        $text = "aliRequestData:" . json_encode(array(
                "data" => $data
            ));
        logOut($text);
    }
    return $res;
}

//删除文件夹
function deldir($dir)
{
    //先删除目录下的文件：
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if ($file != "." && $file != "..") {
            $fullpath = $dir . "/" . $file;
            if (!is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                deldir($fullpath);
            }
        }
    }
    closedir($dh);
    //删除当前文件夹：
    if (rmdir($dir)) {
        return true;
    } else {
        return false;
    }
}

//以xx字符串结束
function str_end_with($str, $one)
{
    return strrpos($str, $one) == strlen($str) - strlen($one);
}

//以xx字符串开始
function str_start_with($str, $one)
{
    return strpos($str, $one) === 0;
}

//日志
function logOut($text)
{
    return;
    $myfile = fopen(dirname(__FILE__) . "log.txt", "a");
    fwrite($myfile, date('Y-m-d H:i:s') . $text . "\n\n");
    fclose($myfile);
}

//文件列表
function file_list($path, $update = false, $rootDir, $driveId, $accessToken)
{
    $file_list = $rootDir . $path . "/file_list.php";
    $item = false;
    if (!$update) {
        if (file_exists($file_list)) {
            $item = get_json($file_list);
        }
    }
    if ($item && count($item) > 0) {
        return $item;
    }
    //创建文件夹
    create_dir($file_list);
    $pid = path2id($rootDir, $path);
    $data = file_list_ajax($pid, $driveId, $accessToken, $rootDir);
    set_json($file_list, $data['items']);
    return $data['items'];
}

//目录文件数量
function path_file_size($rootDir, $path)
{
    $file_list = $rootDir . $path . "/file_list.php";
    $item = false;
    if (file_exists($file_list)) {
        $item = get_json($file_list);
    }
    if ($item && count($item) > 0) {
        return count($item);
    }
    return 0;
}

//文件列表ajax
function file_list_ajax($pid, $driveId, $accessToken, $rootDir)
{
    $data = array("items" => array());
    $marker = false;
    do {
        $tmp = file_list_ajax_marker($pid, $marker, $driveId, $accessToken, $rootDir);
        $tmpItems = $tmp['items'];
        foreach ($tmpItems as $tmpItem) {
            $info = array(
                "type" => $tmpItem['type']
            );
            $info['createTime'] = isset($tmpItem['created_at']) ? strtotime($tmpItem['created_at']) : 0;
            $info['modifyTime'] = isset($tmpItem['updated_at']) ? strtotime($tmpItem['updated_at']) : 0;
            $info['isReadable'] = true;
            $info['isWriteable'] = true;
            $info['file_id'] = $tmpItem['file_id'];
            $info['name'] = $tmpItem['name'];
            if ($info['type'] == "file") {
                $info['size'] = isset($tmpItem['size']) ? $tmpItem['size'] : 0;
                $info['ext'] = $tmpItem['file_extension'];
                $info['thumbnail'] = $tmpItem['thumbnail'];
                $info['content_hash'] = "SHA1:" . $tmpItem['content_hash'];
            }
            array_push($data['items'], $info);
        }
        $marker = $tmp['next_marker'];
    } while ($marker);
    return $data;
}

//文件列表分页
function file_list_ajax_marker($pid, $marker = false, $driveId, $accessToken, $rootDir)
{
    $param = array("parent_file_id" => $pid, "drive_id" => $driveId, "limit" => 200);
    if ($marker) {
        $param['marker'] = $marker;
    }
    $headers = array("Content-Type: application/json",
        "authorization: Bearer " . $accessToken,
        "cache-control: no-cache");
    $data = aliRequest($rootDir, '/adrive/v3/file/list', $param, $headers);
    return $data;
}

function async_action($flag = "0")
{
    if ($flag != "1") {
        return;
    }
    ob_start();
    echo "1";
    $size_o = ob_get_length();
    header("Content-Length: $size_o");
    header('Connection: close');
    header("HTTP/1.1 200 OK");
    header("Content-Type: application/json;charset=utf-8");
    ob_end_flush();
    if (ob_get_length()) {
        ob_flush();
        flush();
    }
    if (function_exists("fastcgi_finish_request")) {
        fastcgi_finish_request();
    }
    ignore_user_abort(true);
    set_time_limit(0);
}

//方法分支
if ($_GET["type"] == "1") {
    //获取下载链接
    $url = $_GET['url'];
    if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
        $size = $_GET['size'];
        header("Content-Length: $size");
        return;
    }
    if (strpos($url, 'x-oss-additional-headers=referer') || $_SERVER['HTTP_REFERER']) {
        $fileName = $_GET['fileName'];
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($curl, CURLOPT_REFERER, 'https://www.aliyundrive.com/');
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_errno($curl);
        curl_close($curl);
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $fileName . '";');
        echo $res;
    } else {
        header('Location: ' . $url);
    }
} else if ($_GET["type"] == "2") {
    //刷新上级目录
    $fileIo = file_get_contents('php://input');
    $data = json_decode($fileIo, true);
    async_action($_GET['async']);
    logOut("刷新上级" . $fileIo);
    file_list($data['path'], true, $data['rootDir'], $data['driveId'], $data['accessToken']);
}
